﻿using NPortableEngine;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using Windows.Storage.Streams;

namespace NCache
{
    internal class CacheDeliver : INDeliver
    {
        public CacheDeliver(Uri uri,Action<Stream> callback)
        {
            Uri = uri;
            Callback = callback;
        }

        public Uri Uri { get; private set; }
        public Action<Stream> Callback { get; set; }
    }

    internal class CacheDeliverExecutor : INDeliverExecutor
    {
        #region Fields
        private bool _isCallback = true;
        private CacheDeliver _cacheDeliver;
        #endregion

        public Action CompleteAciton { get; set; }

        public async void Execute(INDeliver deliver)
        {
            if (deliver is CacheDeliver)
            {
                _isCallback = false;
                _cacheDeliver = (CacheDeliver)deliver;
                Stream stream = await CacheEngine.CacheImage(_cacheDeliver.Uri);
                if (_cacheDeliver.Callback != null)
                {
                    _cacheDeliver.Callback(stream);
                }
                if (CompleteAciton != null)
                {
                    CompleteAciton();
                }
                _isCallback = true;
            }
        }

        public void Cancel()
        {
            _cacheDeliver.Callback(null);
            _cacheDeliver.Callback = null;
            if (CompleteAciton != null)
            {
                CompleteAciton();
            }
            _isCallback = true;
        }

        public bool CheckIsRunning()
        {
            return !_isCallback;
        }
    }
}
